package com.asiainfo.complier.editor;

import javax.swing.text.*;
import java.awt.*;

public class CodeEditorKit extends DefaultEditorKit {
	/**
	 * CodeEditorKit
	 */
	private static final long serialVersionUID = -1397613972468854031L;

	public CodeEditorKit() {
		super();
	}

	public ViewFactory getViewFactory() {
		return new CodeViewFactory();
	}
}

class CodeViewFactory implements ViewFactory {
	public CodeViewFactory() {
	}

	public View create(Element element) {
		return new CodeEditorView(element);
	}
}

class CodeEditorView extends PlainView {
	public CodeEditorView(Element element) {
		super(element);
	}

	@Override
	protected int drawSelectedText(Graphics g, int x, int y, int p0, int p1)
			throws BadLocationException {
		g.setColor(new Color(0x72, 0x00, 0x00));
		g.setFont(f);
		return super.drawSelectedText(g, x, y, p0, p1);
	}

	@Override
	protected int drawUnselectedText(Graphics g, int x, int y, int p0, int p1)
			throws BadLocationException {
		// System.out.println(new JTextArea().getFont());
		Document doc = getDocument();
		Segment segment = new Segment(), token = new Segment();
		int index = 0, count = p1 - p0;
		g.setFont(font);
		g.setColor(new Color(0x72, 0x00, 0x00));
		doc.getText(p0, count, segment);
		for (int i = 0; i < count; i++) {
			if (Character.isLetter(segment.array[segment.offset + i])) {
				index = i;
				while (++i < count
						&& Character
								.isLetter(segment.array[segment.offset + i]))
					;
				doc.getText(p0 + index, (i--) - index, token);
				if (KeyWord.isKeyWord(token)) {
					g.setFont(f);
					g.setColor(KEYWORDCOLOR);
				} else {
					g.setFont(font);
					g.setColor(TEXTCOLOR);
				}
				x = Utilities.drawTabbedText(token, x, y, g, this, p0 + index);
				continue;
			} else {
				index = i;
				while (++i < count
						&& !Character
								.isLetter(segment.array[segment.offset + i]))
					;
				doc.getText(p0 + index, (i--) - index, token);

				g.setColor(TEXTCOLOR);
				x = Utilities.drawTabbedText(token, x, y, g, this, p0 + index);
				continue;
			}
		}
		return x;
	}

	public static Color TEXTCOLOR = Color.black;

	Font f = new Font("dialoginput", Font.PLAIN | Font.BOLD, 12);
	Font font = new Font("dialoginput", Font.PLAIN, 12);

	public static Color KEYWORDCOLOR = Color.blue;
}
